package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Arrays;
import java.util.Objects;

import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author coffee
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        checkIn.setCreateTime(LocalDateTime.now());
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        checkIn.setUpdateTime(LocalDateTime.now());
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        //查询老人信息是否存在
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 1);
        Elder elderQuery = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderQuery)) {
//            throw new RuntimeException("老人已存在");
            return;
        } else {
            //设置床位信息
            bed.setBedStatus(1);
            bedMapper.updateById(bed);
            //设置老人信息并存入数据库
            Elder elder = insertOrUpdate(dto, bed);
            //设置合同信息并存入数据库
            Contract contract = new Contract();
            BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
            contract.setElderId(elder.getId());
            contract.setCreateTime(LocalDateTime.now());
            contract.setContractName("合同");
            contract.setElderName(elder.getName());
            LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
            LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
            Integer status = checkInStartTime.isAfter(LocalDateTime.now()) ? 1 : 0;
            contract.setStatus(status);
            contract.setStartDate(checkInStartTime);
            contract.setEndDate(checkInEndTime);
            contract.setContractNumber("123");
            contractMapper.insert(contract);
            //设置入住信息并存入数据库
            CheckIn checkIn = new CheckIn();
            checkIn.setElderId(elder.getId());
            checkIn.setElderName(elder.getName());
            checkIn.setIdCardNo(elder.getIdCardNo());
            checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
            checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
            checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
            checkIn.setBedNumber(bed.getBedNumber());
            checkIn.setStatus(0);
            checkIn.setCreateTime(LocalDateTime.now());
            checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
            checkInMapper.insert(checkIn);
            //设置入住配置信息并存入数据库
            CheckInConfig checkInConfig = new CheckInConfig();
            BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
            checkInConfig.setCheckInId(checkIn.getId());
            checkInConfigMapper.insert(checkInConfig);
        }
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        //查询四张表的数据
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, checkIn.getElderId())
                .eq(Contract::getStatus, 1)
                .orderByDesc(Contract::getCreateTime)
                .last("limit 1"));
        Elder elder = elderMapper.selectById(checkIn.getElderId());

        CheckInDetailVo vo = new CheckInDetailVo();
        //vo转换
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        vo.setCheckInElderVo(checkInElderVo);
        String remark = checkIn.getRemark();
        if (!Objects.isNull(remark)) {
            List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
            vo.setElderFamilyVoList(elderFamilyVoList);
        }
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        vo.setCheckInConfigVo(checkInConfigVo);
        vo.setContract(contract);
        return vo;
    }

    private Elder insertOrUpdate(CheckInApplyDto dto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        elder.setCreateTime(LocalDateTime.now());
        elderMapper.insert(elder);
        return elder;
    }
}
